import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CategoryDiseaseEntity } from './category-disease.entity';

@Injectable()
export class CategoryDiseaseService {
  constructor(
    @InjectRepository(CategoryDiseaseEntity)
    private readonly categoryDiseaseRepository: Repository<CategoryDiseaseEntity>,
  ) {}

  /**
   * 通过用户ID查询相关联的病症ID列表
   * @param userId 用户ID
   * @returns 病症ID列表
   */
  async findDiseaseIdsByUserId(userId: number): Promise<number[]> {
    // 查询该用户关联的所有病症记录
    const categoryDiseases = await this.categoryDiseaseRepository.find({
      where: {
        user: { id: userId },
      },
      relations: ['category'],
    });

    // 提取并返回病症ID列表
    if (!categoryDiseases || categoryDiseases.length === 0) {
      return [];
    }

    // 从查询结果中提取类别ID
    return categoryDiseases.map(item => item.category?.id).filter(id => id !== undefined);
  }

	/**
	 * 通过用户ID查询单条关联记录的疾病类别ID
	 * @param userId 用户ID
	 * @returns 用户关联的疾病类别ID，如果不存在则返回null
	 */
	async findCategoryIdByUserId(userId: number): Promise<number | null> {
		const relation = await this.categoryDiseaseRepository.findOne({
			where: {
				user: { id: userId },
			},
			relations: ['category'],
		});

		return relation?.category?.id || null;
	}

	/**
	 * 创建或更新用户与疾病类别的关联关系
	 * @param userId 用户ID
	 * @param categoryId 疾病类别ID
	 * @returns 创建或更新的关联记录
	 */
	async createOrUpdateUserDiseaseRelation(userId: number, categoryId: number): Promise<CategoryDiseaseEntity> {
		// 查找是否已存在关联关系
		const existingRelation: CategoryDiseaseEntity = await this.categoryDiseaseRepository.findOne({
			where: {
				user: { id: userId },
			},
			relations: ['category', 'user'],
		});

		if (existingRelation && existingRelation.category?.id) {
			// 更新现有关系中的疾病类别ID
			existingRelation.category = { id: categoryId } as any; // 使用类型断言来设置类别ID
			return this.categoryDiseaseRepository.save(existingRelation);
		} else {
			// 创建新的关联实体
			const newRelation = this.categoryDiseaseRepository.create({
				user: { id: userId },
				category: { id: categoryId },
			});

			// 保存到数据库
			return this.categoryDiseaseRepository.save(newRelation);
		}
	}
}

